package main

import (
	"fmt"
	"net"
	"os"
	"sync"
)

const port = "39876"

func main() {
	f, err := os.Open("main.go")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	laddr, err := net.ResolveTCPAddr("tcp", ":"+port)
	if err != nil {
		panic(err)
	}

	l, err := net.ListenTCP("tcp", laddr)
	if err != nil {
		panic(err)
	}

	wg := &sync.WaitGroup{}
	wg.Add(1)
	go func() {
		c, err := net.Dial("tcp", "127.0.0.1:"+port)
		if err != nil {
			panic(err)
		}
		b := make([]byte, 4096)
		n, err := c.Read(b)
		if err != nil {
			panic(err)
		}
		fmt.Println("-----")
		fmt.Printf("%s", string(b[:n]))
		fmt.Println("-----")
		wg.Done()
	}()

	c, err := l.AcceptTCP()
	if err != nil {
		panic(err)
	}

	// ReadFrom will send byte to peer by using splice/sendfile
	n, err := c.ReadFrom(f)
	if err != nil {
		panic(err)
	}
	fmt.Println("ReadFrom n:", n)

	wg.Wait()
}
